<template>
    <div class="flex-col">

        <n-form
                style="margin-top: 12px"
                ref="formRef"
                :model="formData"
                :rules="rules"
                label-placement="left"
                label-width="140"
                require-mark-placement="right-hanging"
                size="medium"
        >

            <n-form-item label="知识库" path="knowledgeBaseId">
                <jb-select :disabled="props.knowledgeBaseId" v-model:value="formData.knowledgeBaseId"
                           url="/aiKnowledgeBase/listAllEnabled" labelField="name" valueField="id"
                           :filterable="true"></jb-select>
            </n-form-item>
            <n-form-item label="AI资源" path="model">
                <jb-select v-model:value="formData.model" url="/aiResource/listAllEnabledType"
                           labelField="name"
                           valueField="sn" :filterable="true"></jb-select>
            </n-form-item>

            <n-form-item
                    label="上传"
                    path="answer"
            >
                <div >
                    <jb-upload
                        v-model="formData.files"
                        @loadFiles="loadFiles"
                        :multiple="true"
                        :showFileList="false"
                        accept=".pdf, .doc, .docx, .xls, .xlsx, .txt, .md"
                        save-path="vector/{date(yyMMdd)}/{random(6)}/{ori}"
                    >
                        <div class="flex flex-col">
                            <div>
                                <n-button type="primary" ghost>
                                    <template #icon>
                                        <jb-icon :local="true" icon="material-symbols:upload"></jb-icon>
                                    </template>
                                    上传文件
                                </n-button>

                            </div>

                        </div>
                    </jb-upload>
                    <n-alert :show-icon="false"  type="default" class="mt-8">
                        注：1．仅支持pdf,word,excel,txt,markdown, 最大100M
                        <br/>
                        　　2．excel文件请使用模版导入，<n-button @click="downloadTpl" type="info"  size="tiny">点此下载模板</n-button>
                    </n-alert>
                </div>

            </n-form-item>
            <n-form-item label="是否对图片进行OCR识别" path="extractResources">
                <template #label>
                    <div class="flex items-center justify-end">
                        <label>是否开启OCR</label> &nbsp;
                        <n-popover trigger="hover" style="background-color: black;color: white">
                            <template #trigger>
                                <n-button text>
                                    <jb-icon :local="true" icon="mingcute:information-line" class="ms-1" width="18" color="#aaaaaa"></jb-icon>
                                </n-button>
                            </template>
                            <span>
                                    是否将文档内所有图片进行OCR识别，转换为文字。<br/>注意该操作将非常消耗内存和CPU，请根据实际情况选择。
                                    </span>
                        </n-popover>
                    </div>

                </template>
                <n-radio-group v-model:value="formData.ocrImg" name="ocrImg">
                    <n-space>
                        <n-radio  :value="true">
                            是
                        </n-radio>
                        <n-radio  :value="false">
                            否
                        </n-radio>
                    </n-space>
                </n-radio-group>
            </n-form-item>
            <n-form-item label="提取文档内图片等资源" path="extractResources">
                <template #label>
                    <div class="flex items-center justify-end">
                        <label>是否提取资源</label> &nbsp;
                        <n-popover trigger="hover" style="background-color: black;color: white">
                            <template #trigger>
                                <n-button text>
                                    <jb-icon :local="true" icon="mingcute:information-line" class="ms-1" width="18" color="#aaaaaa"></jb-icon>
                                </n-button>
                            </template>
                            <span>
                                    是否将文档内容内的非文字资源保存在系统中，与上下文关联。
                                    </span>
                        </n-popover>
                    </div>

                </template>
                <n-radio-group v-model:value="formData.extractResources" name="extractRadio">
                    <n-space>
                        <n-radio v-for="item in extractResourcesList" :key="item.value" :value="item.value">
                            {{ item.label }}
                        </n-radio>
                    </n-space>
                </n-radio-group>
            </n-form-item>
            <n-form-item label="资源存储" path="resourcesPosition" v-if="formData.extractResources">
                <div class="flex items-center">
                    <n-radio-group v-model:value="formData.resourcesPosition" name="positionRadio">
                        <n-space>
                            <n-radio v-for="item in resourcesPositionList" :key="item.value" :value="item.value">
                                {{ item.label }}
                            </n-radio>
                        </n-space>
                    </n-radio-group>
                    &nbsp; &nbsp; &nbsp;
                    <div class="flex items-center">
                        <div class="flex items-center">
                            <span>存储地址</span> &nbsp;
                            <n-popover trigger="hover">
                                <template #trigger>
                                    <n-button text type="error">
                                        <jb-icon :local="true" icon="mingcute:information-line" class="ms-1" width="18" color="#aaaaaa"></jb-icon>
                                    </n-button>
                                </template>
                                <span>
                                     <n-data-table
                                             size="small"
                                             :bordered="true"
                                             :single-line="false"
                                             :columns="columns"
                                             :data="data"
                                     />


                                </span>
                            </n-popover>
                        </div>
                        &nbsp; &nbsp; &nbsp;
                        <div>
                            <n-input placeholder="请输入存储地址,不指定地址则会默认上传到指定文件的根目录下" v-model:value="formData.resourceSavePath" style="width: 450px" clearable></n-input>
                        </div>
                    </div>
                </div>

            </n-form-item>


        </n-form>

        <n-card style="margin-top: 12px" title="上传文件列表">

            <jb-table
                    :data="list"
                    :style="{ height: '30vh' }"
            >
                <jb-column type="seq" title="序号" width="60" fixed="left"/>

                <jb-column field="fileName" title="文件名" min-width="100"></jb-column>
                <jb-column field="fileType" title="文件类型" min-width="100"></jb-column>
                <jb-column field="fileSize" title="文件大小" min-width="100">
                    <template #default="{ row }">
                        {{ getConvertedSize(row.fileSize) }}
                    </template>
                </jb-column>
                <jb-column field="filePath" title="文件地址" min-width="400"></jb-column>
                <jb-column
                        title="操作"
                        width="100"
                        fixed="right"
                >
                    <template #default="{ row }">
                        <jb-btn
                            :icon="Icons.DELETE"
                            type="error"
                            secondary
                            circle
                            @click="handleDelete(row)"
                        />
                    </template>
                </jb-column>
            </jb-table>
        </n-card>

    </div>

</template>

<script setup>
import {ref, reactive} from 'vue'
import {JBoltApi} from '@/service/request'
import {Icons} from '@/constants'
import {useDialog} from 'naive-ui'
import {useMessage} from 'naive-ui'

const message = useMessage()

const props = defineProps({
    id: [String, Number],
    knowledgeBaseId: String
})

function downloadTpl() {
    const link = document.createElement('a')
    link.href = '/template.xlsx';
    link.download = "QA导入模板.xlsx";
    link.click()
    URL.revokeObjectURL(link.href)
}
const list = ref([])
const extractResourcesList = [
    {
        value: false,
        label: '不提取'
    },
    {
        value: true,
        label: '提取资源'
    },
]
const resourcesPositionList = [
    {
        value: 'qiniu',
        label: '七牛云'
    },
    {
        value: 'local',
        label: '本地'
    },
]
const columns = [
    {
        title: '语法',
        key: 'grammar'
    },
    {
        title: '说明',
        key: 'desc'
    },
    {
        title: '规则举例',
        key: 'rules'
    },
    {
        title: '生成的结果',
        key: 'result'
    }
]
const data = [
    {
        grammar: '{ori}',
        desc: '完整的原文件名',
        rules: '/doc/{ori}',
        result: '/doc/abc.doc'
    },
    {
        grammar: '{oriSuffix}',
        desc: '原文件后缀名',
        rules: '/doc/a.{oriSuffix}',
        result: '/doc/a.doc'
    },
    {
        grammar: '{oriName}',
        desc: '原文件名,不带后缀',
        rules: '/doc/{oriName}_1.doc',
        result: '/doc/abc_1.doc'
    },
    {
        grammar: '{random(位数)}',
        desc: '随机字符',
        rules: '/doc/{random(4)}/{ori}',
        result: '/doc/e5j8/abc.doc'
    },
    {
        grammar: '{date(格式)}',
        desc: '日期',
        rules: '/doc/{date(yyMMddHH)}/{ori}',
        result: '/doc/23102410/abc.doc'
    },
    {
        grammar: '{date}',
        desc: '日期按照 yyyyMMddHHmmss 格式化后的值',
        rules: '/doc/{date}/{ori}',
        result: '/doc/20231024100521/abc.doc'
    },
]

const dialog = useDialog()
function loadFiles(data) {
    console.log('file', data)
    list.value = [...list.value, ...data]
}

function handleDelete(row) {
    dialog.warning({
        title: '提示',
        content: '是否确认删除该文件？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            list.value = list.value.filter(item => item.id !== row.id)
        }
    })

}

const formRef = ref(null)

// 表单数据
const formData = reactive({
    knowledgeBaseId: props.knowledgeBaseId,
    files: '',
    model: '',
    ocrImg: false,
    extractResources: false,
    resourcesPosition: 'qiniu',
    resourceSavePath:'QA/doc/{date(yyMMdd)}/{random(6)}/{ori}'
})


// 表单验证规则
const rules = {
    knowledgeBaseId: {
        required: true,
        message: '请选择知识库',
        trigger: 'change'
    },
    model: {
        required: true,
        message: '请选择AI资源',
        trigger: 'change'
    }
}

// 提交方法
const submit = async (callback) => {
    try {
        await formRef.value?.validate()
        if (!list.value.length) {
            message.error('请先上传文件')
            return
        }

        const params = {
            list: list.value.map(item => {

                let data = {...item}
                delete data.id

                return {
                    ...data,
                    knowledgeBaseId: formData.knowledgeBaseId,
                    docType: 'QA',
                    fileStatus: 0,
                    splitTime: "",
                    trainingTime: "",
                    vectorTime: "",
                    splitRule: "",
                    createdTime: "",
                    ocrImg: formData.ocrImg,
                    extractResources: formData.extractResources,
                    resourcesPosition: formData.extractResources==true?formData.resourcesPosition:"",
                    resourceSavePath:formData.extractResources==true?formData.resourceSavePath:""
                }
            }),
            knowledgeBaseId: formData.knowledgeBaseId,
            model: formData.model,
            docType: 'QA',
            ocrImg: formData.ocrImg,
            extractResources: formData.extractResources,
            resourcesPosition: formData.extractResources==true?formData.resourcesPosition:"",
            resourceSavePath:formData.extractResources==true?formData.resourceSavePath:""
        }

        await JBoltApi.post('/aiFile/batchAdd', params, {
            ignoreMsg: true
        })
        callback?.()
    } catch (error) {
        console.error(error)
    }
}
// 计算属性，根据文件大小决定显示格式
const getConvertedSize = (kb) => {
    if (kb < 1024) {
        return `${kb} KB`;
    }
    return `${(kb / 1024).toFixed(2)} MB`;
};

defineExpose({
    submit
})
</script>